/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultarReceitas.java
 *
 * Created on 30/10/2009, 20:10:00
 */

package gerenciadorfinanceiro.view.resources;

import gerenciadorfinanceiro.Utilitario;
import gerenciadorfinanceiro.database.resources.Income;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Action;

/**
 *
 * @author eduardo
 */
public class ConsultarReceitas extends javax.swing.JDialog {

    /** Creates new form ConsultarReceitas */
    public ConsultarReceitas() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlDados = new javax.swing.JPanel();
        lblMes = new javax.swing.JLabel();
        cbxMes = new javax.swing.JComboBox();
        lblAno = new javax.swing.JLabel();
        cbxAno = new javax.swing.JComboBox();
        btnPesquisar = new javax.swing.JButton();
        btnLimpar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblReceitas = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getResourceMap(ConsultarReceitas.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        pnlDados.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        pnlDados.setName("pnlDados"); // NOI18N

        lblMes.setText(resourceMap.getString("lblMes.text")); // NOI18N
        lblMes.setName("lblMes"); // NOI18N

        cbxMes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbxMes.setName("cbxMes"); // NOI18N

        lblAno.setText(resourceMap.getString("lblAno.text")); // NOI18N
        lblAno.setName("lblAno"); // NOI18N

        cbxAno.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbxAno.setName("cbxAno"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(gerenciadorfinanceiro.GerenciadorFinanceiroApp.class).getContext().getActionMap(ConsultarReceitas.class, this);
        btnPesquisar.setAction(actionMap.get("pesquisarDespesas")); // NOI18N
        btnPesquisar.setText(resourceMap.getString("btnPesquisar.text")); // NOI18N
        btnPesquisar.setName("btnPesquisar"); // NOI18N

        btnLimpar.setAction(actionMap.get("LimparTabelaDespesas")); // NOI18N
        btnLimpar.setText(resourceMap.getString("btnLimpar.text")); // NOI18N
        btnLimpar.setEnabled(false);
        btnLimpar.setName("btnLimpar"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tblReceitas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblReceitas.setName("tblReceitas"); // NOI18N
        jScrollPane1.setViewportView(tblReceitas);

        javax.swing.GroupLayout pnlDadosLayout = new javax.swing.GroupLayout(pnlDados);
        pnlDados.setLayout(pnlDadosLayout);
        pnlDadosLayout.setHorizontalGroup(
            pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlDadosLayout.createSequentialGroup()
                        .addComponent(btnPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnLimpar, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlDadosLayout.createSequentialGroup()
                        .addComponent(lblMes)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbxMes, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblAno)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbxAno, 0, 220, Short.MAX_VALUE)))
                .addContainerGap())
        );
        pnlDadosLayout.setVerticalGroup(
            pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblMes)
                    .addComponent(cbxMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblAno)
                    .addComponent(cbxAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPesquisar)
                    .addComponent(btnLimpar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 273, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        Calendar c = new GregorianCalendar();
        int atual = c.get(Calendar.YEAR);
        int mesAtual = c.get(Calendar.MONTH);

        c.add(Calendar.YEAR, -5);

        cbxAno.removeAllItems();

        int year = c.get(Calendar.YEAR);

        for (int i = 0; i < 10; i++) {
            cbxAno.addItem(year+i);
        }

        cbxAno.setSelectedItem(atual);

        cbxMes.removeAllItems();

        for(String s: meses) {
            cbxMes.addItem(s);
        }

        cbxMes.setSelectedIndex(mesAtual);

        this.LimparTabelaDespesas();
        tblReceitas.setVisible(false);
    }//GEN-LAST:event_formComponentShown
  
    @Action
    public void pesquisarDespesas() {
        List<Income> incomes = this.getUtil().getIncomeDAO().getIncomes(this.getUtil().getLoggedUser(), cbxMes.getSelectedIndex() + 1, ((Integer)cbxAno.getSelectedItem()).intValue());

        DefaultTableModel tm = new DefaultTableModel();
        tm.setColumnIdentifiers(columns);

        DecimalFormat formatador  = new DecimalFormat();
        formatador.applyPattern("R$ ###,##0.00;R$ (###,##0.00)");

        for(Income i: incomes) {
            tm.addRow(new Object[] {i.getId().toString(), i.getData(), i.getDescriptionIncome(), formatador.format(i.getValue())});
        }

        tblReceitas.setModel(tm);

        tblReceitas.setAutoCreateColumnsFromModel(false);

        // Ordena todas as linhas de forma decrescente de acordo com os
        // valores da segunda coluna do modelo
        sortAllRowsBy(tm, 1, true);

        tblReceitas.setVisible(true);

        btnLimpar.setEnabled(true);
        btnPesquisar.setEnabled(false);
        cbxAno.setEnabled(false);
        cbxMes.setEnabled(false);
    }

    public void sortAllRowsBy(DefaultTableModel model, int colIndex,
                              boolean ascending) {
        Vector data = model.getDataVector();
        Collections.sort(data, new ColumnSorter(colIndex, ascending));
        model.fireTableStructureChanged();
    }

    /**
     * @return the util
     */
    public Utilitario getUtil() {
        return util;
    }

    /**
     * @param util the util to set
     */
    public void setUtil(Utilitario util) {
        this.util = util;
    }

    class ColumnSorter implements Comparator {
        int colIndex;
        boolean ascending;
        ColumnSorter(int colIndex, boolean ascending) {
            this.colIndex = colIndex;
            this.ascending = ascending;
        }
        public int compare(Object a, Object b) {
            Vector v1 = (Vector)a;
            Vector v2 = (Vector)b;
            Object o1 = v1.get(colIndex);
            Object o2 = v2.get(colIndex);

            if (o1 instanceof String && ((String)o1).length() == 0) {
                o1 = null;
            }
            if (o2 instanceof String && ((String)o2).length() == 0) {
                o2 = null;
            }

            if (o1 == null && o2 == null) {
                return 0;
            } else if (o1 == null) {
                return 1;
            } else if (o2 == null) {
                return -1;
            } else if (o1 instanceof Comparable) {
                if (ascending) {
                    return ((Comparable)o1).compareTo(o2);
                } else {
                    return ((Comparable)o2).compareTo(o1);
                }
            } else {
                if (ascending) {
                    return o1.toString().compareTo(o2.toString());
                } else {
                    return o2.toString().compareTo(o1.toString());
                }
            }
        }
    }

    @Action
    public void LimparTabelaDespesas() {
        DefaultTableModel tm = new DefaultTableModel();
        tm.setColumnIdentifiers(columns);

        tblReceitas.setModel(tm);

        tblReceitas.setAutoCreateColumnsFromModel(false);

        tblReceitas.setVisible(true);

        btnLimpar.setEnabled(false);
        btnPesquisar.setEnabled(true);
        cbxAno.setEnabled(true);
        cbxMes.setEnabled(true);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnPesquisar;
    private javax.swing.JComboBox cbxAno;
    private javax.swing.JComboBox cbxMes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAno;
    private javax.swing.JLabel lblMes;
    private javax.swing.JPanel pnlDados;
    private javax.swing.JTable tblReceitas;
    // End of variables declaration//GEN-END:variables

    private String[] columns = {"Id", "Data", "Descricao","Valor"};
    private String[] meses = {"Janeiro","Fevereiro","Marco","Abril","Maio","Junho","Julho",
        "Agosto","Setembro", "Outubro", "Novembro", "Dezembro"};

    private Utilitario util;
    
}
